import os

import win32api
import win32con
import win32gui
from selenium import webdriver
import time

from selenium.webdriver.common.by import By

## 移除背景的工具

# 打开浏览器
driver = webdriver.Chrome()
# 设置浏览器最大化
driver.maximize_window()
# 设置隐式等待
driver.implicitly_wait(10)
# 打开网页
driver.get(r'https://www.quzuotu.com/segment/index/')
time.sleep(1)

def clickReLoad():
    while True:
        try:
            upload = driver.find_element(By.CSS_SELECTOR,'#app > div.page-container > div:nth-child(1) > div.topbar > div.icon_txt_btn.reupload')
            upload.click()
            break
        except:
            print('请先扫描验证码')
        else:
            print('点击 重新上传')
        finally:
            time.sleep(1)
def uploadImage(filePath):
    dialog = win32gui.FindWindow('#32770', u'打开')
    ChomboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None)
    ComboBox = win32gui.FindWindowEx(ChomboBoxEx32, 0, 'ComboBox', None)
    Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None)

    # button = win32gui.FindWindowEx(dialog, 0, 'Button', None)
    button = win32gui.FindWindowEx(dialog, None, 'Button', None)

    if Edit is not None and button is not None:
        time.sleep(1)
        win32gui.SendMessage(Edit, win32con.WM_SETTEXT, None, filePath)
        time.sleep(1)

        # 模拟按下 Enter 键
        win32api.keybd_event(win32con.VK_RETURN, 0, 0, 0)
        win32api.keybd_event(win32con.VK_RETURN, 0, win32con.KEYEVENTF_KEYUP, 0)

        time.sleep(5)

def dowloadImage():
    while True:
        try:
            download = driver.find_element(By.CSS_SELECTOR,
                                            '#app > div.page-container > div:nth-child(1) > div.topbar > div.icon_txt_btn.download')
            download.click()
            time.sleep(0.5)

            confirm = driver.find_element(By.CSS_SELECTOR,
                                           '#app > div.page-container > div:nth-child(7) > div.dialog-content > div > div.download_wrap')
            confirm.click()
            time.sleep(0.5)
        except:
            print('等待下载 请先扫码')
        else:
            print("等待下载 点击下载")
            break
        finally:
            time.sleep(1)


# clickReLoad()
# uploadImage(r'D:\AAA\图文\姿势表情\姿势表情-移除水印\image0.png')
# dowloadImage()


dirPath = r'D:\AAA\图文\姿势表情\姿势表情-移除水印'
targetPath = r'D:\AAA\图文\姿势表情\姿势表情-移除背景'
names = os.listdir(dirPath)
for name in names:
    filePath = os.path.join(dirPath, name)
    print(filePath)
    clickReLoad()
    uploadImage(filePath)
    dowloadImage()


print('全部完成')

# 定位搜素框
#element = driver.find_element(By.ID, 'kw')
